﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LotteryVote.Logic.Application;
using LotteryVote.Logic.Limit;
using LotteryVote.Entity;
using LotteryVote.Logic;
using LotteryVote.Utility;
using LotteryVote.Logic.Web;
using LotteryVote.Logic.Exceptions;
using System.Text.RegularExpressions;

namespace LotteryVote
{
    public partial class UpperLimitPanel : CompanyPage
    {
        static IDictionary<int, LotteryCompany> companyDic = new Dictionary<int, LotteryCompany>();
        IList<LotteryCompany> TodayCompany;
        BetUpperLimitFacade blLimit = new BetUpperLimitFacade();
        public bool IsAutoRefresh
        {
            get
            {
                return Request["AutoRefresh"] == "true";
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Execute(() =>
            {
                InitParams();
            });
        }

        void InitParams()
        {
            if (IsAutoRefresh)
            {
                Literal ltlAutoRefresh = new Literal();
                ltlAutoRefresh.ID = "ltl_autoRefresh";
                ltlAutoRefresh.Text = "<meta http-equiv=\"refresh\" content=\"10\">";
                Header.Controls.Add(ltlAutoRefresh);
            }
            TodayCompany = TodayLotteryCompany.Instance.GetTodayCompany();
            if (!IsPostBack)
            {
                BindLimits();
                BindGameType();
            }
        }

        void BindGameType()
        {
            Execute(() =>
            {
                ddl_game.DataSource = EnumHelper.GetDescription<GameTypeEnum>();
                ddl_game.DataValueField = "Value";
                ddl_game.DataTextField = "Description";
                ddl_game.DataBind();
            });
        }
        void BindLimits(bool search = false)
        {
            Execute(() =>
            {
                rpt_2D.DataSource = GetSource(search);
                rpt_2D.DataBind();
            });
        }
        IEnumerable<BetUpperLimit> GetSource(bool search)
        {
            var limitList = LimitContext.Instance.CacheUpperLimitList;
            IEnumerable<BetUpperLimit> source;
            if (!search)
            {
                var rule = GetNumLenRule();
                source = limitList.Where(it => rule.IsMatch(it.Num)).OrderByDescending(it => it.TotalBetAmount).Take(100);
            }
            else
            {
                string num = txt_num.Text;
                int gameplayway = lv_gameplayway.GamePlayWayId;
                int companyId = lv_company.SelectedValue;
                source = limitList.Where(it => it.Num == num);
                if (gameplayway > 0)
                    source = source.Where(it => it.GamePlayWayId == gameplayway);
                if (companyId > 0)
                    source = source.Where(it => it.CompanyId == companyId);
            }
            return source;
        }

        Regex GetNumLenRule()
        {
            int game;
            if (!string.IsNullOrEmpty(Request["Game"]) && int.TryParse(Request["Game"], out game))
            {
                GameTypeEnum gameType = (GameTypeEnum)game;
                ddl_game.SelectedValue = Request["Game"];
                switch (gameType)
                {
                    case GameTypeEnum.ThreeDigital: return new Regex(@"^\d{3}$");
                    case GameTypeEnum.FourDigital: return new Regex(@"^\d{4}$");
                    case GameTypeEnum.FiveDigital: return new Regex(@"^\d{5}$");
                    case GameTypeEnum.PL2: return new Regex(@"^\d{2}#\d{2}$");
                    case GameTypeEnum.PL3: return new Regex(@"^\d{2}#\d{2}#\d{2}$");
                    default: return new Regex(@"^\d{2}$");
                }
            }
            else
                return new Regex(@"^\d{2}$");   //默认是2位
        }

        public string ParseGamePlayWay(object gpwObj)
        {
            int gpwId = Convert.ToInt32(gpwObj);
            var gpw = LotterySystem.Current.FindGamePlayWay(gpwId);
            return string.Format("{0} {1}", gpw.GameType.GameName, string.IsNullOrEmpty(gpw.PlayWay.WayName)? string.Empty : GetGlobalResourceObject("Resource", gpw.PlayWay.WayName));
        }

        public LotteryCompany ParseCompany(object company)
        {
            int companyId = Convert.ToInt32(company);
            if (!companyDic.ContainsKey(companyId))
            {
                var com = TodayCompany.Find(it => it.CompanyId == companyId);
                companyDic.Add(companyId, com);
            }
            return companyDic[companyId];
        }
        public string GetColClass(object totalAmount, object upperLimit, object stopBet)
        {
            if ((bool)stopBet) return "canceld";
            return (decimal)totalAmount > ((decimal)upperLimit) * (decimal)0.8 ? "willFull" : string.Empty;
        }

        protected void rpt_2D_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            Execute(() =>
            {
                int limitId = Convert.ToInt32(e.CommandArgument);
                switch (e.CommandName)
                {
                    case "Start": StartBet(limitId); break;
                    case "Stop": StopBet(limitId); break;
                }
                BindLimits();
            });
        }

        void StartBet(int limitId)
        {
            blLimit.StartAcceptBet(limitId, CurrentUser);
        }
        void StopBet(int limitId)
        {
            blLimit.StopAcceptBet(limitId, CurrentUser);
        }

        protected void btn_Search_Click(object sender, EventArgs e)
        {
            BindLimits(true);
        }

    }
}